package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.entity.ShopGoods;
import com.entity.ShopOrder;
import com.entity.Userinfo;
import com.service.ShopOrderService;
import com.util.CookieUtil;
import com.util.MailUtils;
import com.util.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class ShopOrderController {

    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private HttpSession session;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private MailUtils mailUtils;

    @RequestMapping("/getAllOrder")
    public String getAllOrder(Model model) {
        List<ShopOrder> allOrder = shopOrderService.findAllOrder();
        model.addAttribute("ordersList", allOrder);
        return "order/list";
    }

    @RequestMapping("/produceOrder")
    public void produceOrder(Integer[] cartCheckBox, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        if (null != cartCheckBox) {
            Object obj = session.getAttribute("mp");
            Map<Integer, ShopGoods> map = (Map<Integer, ShopGoods>) obj;
            if (null != obj) {
                ArrayList<ShopGoods> buyLists = new ArrayList<>();
                for (Integer id : cartCheckBox) {
                    if (map.containsKey(id)) {
                        ShopGoods goods = map.get(id);
                        buyLists.add(goods);
                        map.remove(id);
                    }
                }
                ShopOrder order = new ShopOrder();
                Userinfo user = (Userinfo) session.getAttribute("user");
                String loginName = user.getLoginName();
                if (loginName != null) {
                    order.setLoginName(loginName);
                }
                shopOrderService.calculateProducts(buyLists, order);
            }
            if (map != null && map.size() > 0) {
                out.write("<script>alert('购买成功')location.href='cart'</script>");
            } else {

                out.write("<script>alert('购买成功');location.href='getGoodsByPage'</script>");
            }
        } else {
            out.write("<script>alert('请选择要购买的商品')history.go(-1)</script>");

        }
    }

    private String token() {
        return CookieUtil.readCookieToken(request);
    }

    @RequestMapping("/produceOrder2")
    public void produceOrder2(Integer[] cartCheckBox, HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String jsonGoods ="";
        List<String> photoList = new ArrayList<>();
        String fileList="";
        double sum = 0.0;
        if (null != cartCheckBox) {
            List<ShopGoods> list = null;
            String dbStr = redisUtil.get(token());
            if (null == dbStr) {
                list = new ArrayList<ShopGoods>();
            } else {
                list = JSON.parseArray(dbStr, ShopGoods.class);

                for (int i=0; i<list.size();i++) {
                    jsonGoods+=list.get(i).getName()+",数量为"+list.get(i).getNumber();
                    sum+=list.get(i).getNumber()*list.get(i).getPrice();
                    if(i==0){
                        fileList+=list.get(i).getFileName();
                    }else{
                       fileList+= ","+list.get(i).getFileName();
                    }

                }
//                fileList = JSON.toJSONString(photoList);

                System.out.println(photoList);
                jsonGoods+="\n,总计为:"+sum;
            }
            if (list != null) {
                ArrayList<ShopGoods> buyLists = new ArrayList<>();
                for (Integer id : cartCheckBox) {
                    for (int index = 0; index < list.size(); index++) {
                        if (list.get(index).getId().equals(id)) {
                            ShopGoods goods = list.get(index);
                            buyLists.add(goods);
                            list.remove(index);
                        }
                    }
                }
                ShopOrder order = new ShopOrder();
                String loginName = (String) session.getAttribute("loginName");
                if (loginName != null) {
                    order.setLoginName(loginName);
                }
                shopOrderService.calculateProducts(buyLists, order);
            }
            String saveStr = JSON.toJSONString(list);


            redisUtil.set(token(), saveStr);
            String token = CookieUtil.readCookieToken(request);
            String userKey = DigestUtils.md5Hex(token);
            String userRedis = redisUtil.get(userKey);
            JSONObject jsonInfo = JSONObject.parseObject(userRedis);
            String email = (String) jsonInfo.get("email");
            String userName = (String) jsonInfo.get("userName");
            String sex = (String) jsonInfo.get("sex");
            String flag="先生";
            if(sex.equals("女")){
                flag="女士";
            }

            try {
                mailUtils.sendMain(true, "购买成功,请核对信息", "尊敬的"+userName+flag+"+fla,\n\n 您在舒老板的店铺中购买的商品如下"+jsonGoods+
                        "\n已支付成功,请查看附件核对信息哦。", email,fileList);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            if (list != null && list.size() > 0) {
                out.write("<script>alert('购买成功');location.href='cart'</script>");
            } else {
                out.write("<script>alert('购买成功');location.href='getGoodsByPage'</script>");
            }
        } else {
            out.write("<script>alert('请选择要购买的商品');history.go(-1)</script>");

        }
    }
}
